<template>
  <div class="home_container">
    <div class="header" @click="toCart">点击跳转购物车</div>
    <div class="list_content">
      <div class="list_item" 
      v-for="(item,index) in listItems" :key="index">
        <div class="item_img">
          <img :src="item.img" alt="">
        </div>
        <div class="item_title">{{item.name}}</div>
        <div class="item_price">￥{{item.price}}</div>
        <div class="item_button" @click="addCart(item)">加入购物车</div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'Home',
  components: {
    
  },
  data(){
    return {
      listItems:[],
      cartItems: JSON.parse(localStorage.getItem('carts')) || []
    }
  },
  methods:{
    toCart(){
      this.$router.history.push('/cart')
    },
    addCart(item){
      this.$store.dispatch('ADD_CART',item)
      
      var status = JSON.parse(localStorage.getItem('login'))
      if(status){
        this.$router.history.push('/')
      }else{
        this.$router.history.push('/cart')
      }
    }
  },
  mounted(){
    axios.get('http://localhost:8080/data.json').then((res)=>{
      console.log(res.data.list)
      this.listItems = res.data.list
    }).catch((error)=>{
      console.log(error)
    })
  }
}
</script>

<style scoped>
  .home_container {
    width: 100%;
  }
  .header {
    width: 100%;
    height: 64px;
    background-color: black;
    color: #fff;
    display: inline-flex;
    justify-content: center;
    align-items: center;
  }
  .list_content {
    width: 100%;
    display: inline-flex;
    justify-content: flex-start;
    align-content: center;
    flex-wrap: wrap;
  }
  .list_item {
    width: 45%;
    height: 300px;
    border: 2px solid gray;
    border-radius: 5px;
    margin-left: 2.5%;
    margin-top: 2.5%;
  }
  .item_img {
    width: 100%;
    border-bottom: 1px solid gray;
  }
  .item_img img {
    width: 100%;
  }
  .item_title {
    font-size: 12px;
    width: 90%;
    margin-left: 5%;
    height: 30px;
    display: inline-flex;
    justify-content: flex-start;
    align-items: center;
    overflow:hidden;
    text-overflow:ellipsis;
    white-space:nowrap;
  }
  .item_price {
    width: 90%;
    margin-left: 5%;
    width: 100%;
    height: 30px;
    color: red;
    display: inline-flex;
    justify-content: flex-start;
    align-items: center;
  }
  .item_button {
    margin-top: 20px;
    width: 90%;
    height: 40px;
    margin-left: 5%;
    border-radius: 5px;
    background-color: red;
    color: #fff;
    display: inline-flex;
    justify-content: center;
    align-items: center;
    font-weight: 700;
  }
</style>
